import store from "/store/index.js";

// 封装微信请求方法
// name:接口名
// data:接口入参
const uniCloudCallFunction = async ({
	name,
	action,
	data
}) => {
	store.commit('showLoading');
	console.log("uniCloudCallFunction name: ", name);
	let token = uni.getStorageSync('login').token || "";
	// token = "1234567890"; // 测试
	if (!name) {
		uni.showToast({
			icon: "none",
			title: "请检查接口名！",
			duration: 3000,
		});
		return;
	}
	const cloudRes = await uniCloud.callFunction({
		name,
		data: {
			action,
			token,
			...data
		}
	});
	setTimeout(() => store.commit('hideLoading'));
	// code 0-失败；1-成功，-1-登录失效
	if (cloudRes && cloudRes.result && cloudRes.result.code === 1) {
		// 正常业务返回
		return cloudRes.result.data;
	} else if (cloudRes && cloudRes.result && cloudRes.result.code === 401) {
		// 登录失效
		// TODO:ZK
		uni.showToast({
			icon: "none",
			title: "登录已失效，正在重新登录，请稍后！",
			duration: 3000,
		});
		setTimeout(() => {
			store.commit('login/clearLoginInfo');
			uni.reLaunch({
				url: "/pages/home/index/index"
			});
		}, 1500);
	} else {
		// 异常业务反馈
		uni.showToast({
			icon: "none",
			title: (cloudRes && cloudRes.result && cloudRes.result.msg) ? cloudRes.result.msg : "参数错误！",
			duration: 3000,
		});
	}
};

export default uniCloudCallFunction;